-- 获取 SKU 键数组和购买数量数组
local sku_keys = KEYS
local buy_quantities = ARGV

local failed_skus = {} -- 失败的 SKU 键数组


-- 检查数组长度是否一致
if #sku_keys ~= #buy_quantities then
    return 0
end

-- 预检查库存是否充足
for i = 1, #sku_keys do
    local sku_key = sku_keys[i]
    local buy_quantity = tonumber(buy_quantities[i])
    local current_stock = tonumber(redis.call('GET', sku_key))

    if not current_stock or current_stock < buy_quantity then
        table.insert(failed_skus, sku_key)
    end
end

if #failed_skus > 0 then
    return 0
    --return {0, failed_skus} -- 返回失败和扣减失败的 SKU 列表
else
    for i = 1, #sku_keys do
        local sku_key = sku_keys[i]
        local buy_quantity = tonumber(buy_quantities[i])
        redis.call('DECRBY', sku_key, buy_quantity)
    end
    return 1 -- 返回成功
end

-- 如果所有 SKU 库存都充足，则批量扣减库存
for i = 1, #sku_keys do
    local sku_key = sku_keys[i]
    local buy_quantity = tonumber(buy_quantities[i])
    redis.call('DECRBY', sku_key, buy_quantity)
end

return 1 -- 返回成功
